package com.pinecone.service.impl;

import com.pinecone.common.Constant.RoleConstant;
import com.pinecone.common.exception.MinerException;
import com.pinecone.common.utils.JwtTokenUtil;
import com.pinecone.dao.CusHostDao;
import com.pinecone.dto.UserDetailsDTO;
import com.pinecone.entity.CusHostEntity;
import com.pinecone.service.CusHostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.pinecone.dao.CusPrincipalDao;
import com.pinecone.entity.CusPrincipalEntity;
import com.pinecone.service.CusPrincipalService;



@Service("cusPrincipalService")
public class CusPrincipalServiceImpl implements CusPrincipalService {
    protected final static Logger logger = LoggerFactory.getLogger(CusPrincipalServiceImpl.class);
	@Autowired
	private CusPrincipalDao cusPrincipalDao;
    @Autowired
    AuthenticationManager myAuthenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private CusHostDao cusHostDao;
    @Autowired
    private CusHostService cusHostService;
	@Override
	public CusPrincipalEntity queryObject(Integer cusId){
		return cusPrincipalDao.queryObject(cusId);
	}
	
	@Override
	public List<CusPrincipalEntity> queryList(Map<String, Object> map){
		return cusPrincipalDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return cusPrincipalDao.queryTotal(map);
	}
	
	@Override
	public void save(CusPrincipalEntity cusPrincipal){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPwd = cusPrincipal.getCusPassword();
        //设置默认属性
        cusPrincipal.setCusPassword(encoder.encode(rawPwd))
                .setLastPasswordResetDate(new Date())
                .setCreateTime(new Date())
                .setState(true);
        logger.info("系统用户注册成功:",cusPrincipal);
		cusPrincipalDao.save(cusPrincipal);
	}
	
	@Override
	public void update(CusPrincipalEntity cusPrincipal){
		cusPrincipalDao.update(cusPrincipal);
	}
	
	@Override
	public void delete(Integer cusId){
		cusPrincipalDao.delete(cusId);
	}
	
	@Override
	public void deleteBatch(Integer[] cusIds){
		cusPrincipalDao.deleteBatch(cusIds);
	}

    @Override
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username+":"+ RoleConstant.ORGUSER, password);
        String token = "";
        try {
            //身份认证
            final Authentication authentication = myAuthenticationManager.authenticate(upToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            final UserDetailsDTO userDetails = userDetailsService.loadUserByUsername(username+":"+ RoleConstant.ORGUSER);
            token = (jwtTokenUtil.generateToken(userDetails));

        } catch (UsernameNotFoundException e) {
            throw new MinerException("用户名或密码错误!",4001);
        } catch (LockedException e){
            throw new MinerException("用户已被锁定!",4002);
        } catch (InternalAuthenticationServiceException e){
            throw new MinerException("用户未被授予角色或权限!",4003);
        } catch (DisabledException e){
            throw new MinerException("用户不存在!",4004);
        }
        return token;
    }

    /**
     * 禁用某个主播
     * @param customerId
     */
    @Override
    public void forbidHost(Integer customerId) {
        CusPrincipalEntity principalEntity = cusPrincipalDao.queryObject(customerId);
        principalEntity.setState(false);
        cusPrincipalDao.update(principalEntity);
    }

    /**
     * 密码重置
     * @param customerId
     */
    @Override
    public void resetPwd(Integer customerId) {
        //查找账号主播信息
        CusHostEntity hostEntity = cusHostDao.queryByCusId(customerId);
        CusPrincipalEntity principalEntity = cusPrincipalDao.queryObject(customerId);
        String phone = hostEntity.getHostPhone();
        final String rawPassword = phone.substring(
                phone.length()-6,phone.length());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        principalEntity.setCusPassword(encoder.encode(rawPassword));
        cusPrincipalDao.update(principalEntity);
    }

    @Override
    public CusPrincipalEntity queryByAccount(String username) {
        return cusPrincipalDao.queryByAccount(username);
    }


}
